package org.cocos2dx.lib;

import android.graphics.Bitmap;

import java.nio.ByteBuffer;

import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Administrator on 2017/8/8.
 */
public class ScreenShotGL10 {
    private static int width;
    private static int height;
    public static GL10 gl;

    public static void setWidth(int width) {
        ScreenShotGL10.width = width;
    }

    public static void setHeight(int height) {
        ScreenShotGL10.height = height;
    }

    public static void setGl(GL10 gl) {
        ScreenShotGL10.gl = gl;
    }

    public static Bitmap getScreenShotBitmap() {
        ByteBuffer buffer = ByteBuffer.allocateDirect(width * height * 4);
        gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, buffer);
        byte[] tmp1 = new byte[width * 4];
        byte[] tmp2 = new byte[width * 4];
        int h = (int) height / 2;
        for (int y = 0; y < h; y++) {
            buffer.position(y * width * 4);
            buffer.get(tmp1, 0, tmp1.length);
            buffer.position((height - 1 - y) * width * 4);
            buffer.get(tmp2, 0, tmp2.length);
            buffer.position((height - 1 - y) * width * 4);
            buffer.put(tmp1);
            buffer.position(y * width * 4);
            buffer.put(tmp2);
        }
        buffer.position(0);
        tmp1 = tmp2 = null;
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        buffer = null;
        System.gc();
        return bitmap;
    }
}
